<?php
/**
 * Created by PhpStorm.
 * User: 李一瑶
 * Date: 2019/1/10
 * Time: 11:43
 */

namespace App\Http\Repository;

use App\Events\UserLoginEvent;
use App\Http\Model\User;
use App\Http\Service\UserInterface;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;


class UserRepository implements UserInterface
{
    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function login(array $data)
    {
        $token = Auth::guard('web')->attempt(['name' => $data['username'],'password' => $data['password']]);
        if($token)
        {
            $id = Auth::user()->id;
            $token = 'Bearer '.$token;
            Cache::put($token,$id,1440);
            $all = [
                'id' => $id,
                'username' => Auth::user()->name,
                'email' => Auth::user()->email,
                'token' => $token,
            ];
            event(new UserLoginEvent(Auth::user()->name));
            return view('User/Home/index',['data'=>$all]);
        }else{
            return back()->with('error','用户名或密码错误！');
        }
    }

    public function regist(array $data)
    {
        $info['password'] = bcrypt($data['password']);
        $info['name'] = $data['username'];
        $info['email'] = $data['email'];
        $re = $this->user->create($info);
        if($re)
        {
           return redirect('/')->with('success','注册成功，请登陆');
        }else{
            return back()->with('error','操作频繁请稍后再试！');
        }
    }

    public function getList(array $data)
    {
        $count = $this->user->count();
        $data1 = $this->user
            ->skip(($data['pageNum'] - 1) * $data['pageSize'])
            ->take($data['pageSize'])
            ->orderBy('id', 'desc')
            ->get()->toArray();
        return response()->json(['code' => 200,'data' => ['data' => $data1,'count' => $count], 'message' => '获取操作日志列表成功']);
    }
}